package com.wcpdoc.base.service.impl;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.wcpdoc.base.entity.Label;
import com.wcpdoc.base.service.LabelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.wcpdoc.auth.realm.JWTRealm;
import com.wcpdoc.base.entity.Org;
import com.wcpdoc.base.entity.User;
import com.wcpdoc.base.entity.UserRowData;
import com.wcpdoc.base.service.OrgService;
import com.wcpdoc.base.service.UserExService;
import com.wcpdoc.base.service.UserService;
import com.wcpdoc.core.dao.BaseDao;
import com.wcpdoc.core.exception.MyException;
import com.wcpdoc.core.service.impl.BaseServiceImp;
import com.wcpdoc.core.util.ValidateUtil;
import com.wcpdoc.file.entity.FileEx;
import com.wcpdoc.file.service.FileService;

/**
 * 用户扩展服务层实现
 * <p>
 * v1.0 zhanghc 2021年10月15日下午1:44:08
 */
@Service
public class UserExServiceImpl extends BaseServiceImp<Object> implements UserExService {

    private static final Logger log = LoggerFactory.getLogger(UserExServiceImpl.class);
    @Resource
    private JWTRealm jwtRealm;
    @Resource
    private FileService fileService;
    @Resource
    private OrgService orgService;

    @Resource
    private LabelService labelService;

    @Resource
    private UserService userService;

    /**
     * 用户导入表结构
     * 用户导入
     * 说明：密码不填，默认为111111
     * 姓名*	登录账号*	机构名称*	密码		邮箱			手机号
     * 张三	zs		山西分部	s36852	xm@qq.com	13000000000
     * 李四	ls		山西软件部
     * 王五	ww		山西运维部
     * 赵六	zl		山西研发组
     * 田七	tq		山西测试组
     */
    @Override
    public void xlsImport(Integer fileId) {
        // 校验数据有效性
        List<Org> orgList = orgService.getList();
        List<Label> labelList = labelService.getList();

        Map<String, Org> orgCache = new HashMap<>();
        Map<String, Label> labelCache = new HashMap<>();


        for (Org org : orgList) {
            orgCache.put(org.getName(), org);// 机构名称是唯一的
        }

        for (Label label : labelList) {
            labelCache.put(label.getName(), label);// 机构名称是唯一的
        }


        Map<String, User> userCache = new HashMap<>();
        List<User> userList = userService.getList();
        for (User user : userList) {
            userCache.put(user.getLoginName(), user);
        }
        Integer AdminId = getCurUser().getId();
        FileEx fileEx = fileService.getFileEx(fileId);
        log.info("=========用户导入");
        EasyExcel.read(fileEx.getFile(), UserRowData.class, new PageReadListener<UserRowData>(userRowList -> {
            for (UserRowData userRowData : userRowList) {
                if (!ValidateUtil.isValid(userRowData.getName())) {
                    continue;// 添加后删除，excel还是能解析到。处理方式为姓名为空，直接处理下一行
//					throw new MyException(String.format("姓名为必填项"));
                }
                if (!ValidateUtil.isValid(userRowData.getLoginName())) {
                    throw new MyException(String.format("登录账号为必填项"));
                }
                if (!ValidateUtil.isValid(userRowData.getOrgName())) {
                    throw new MyException(String.format("机构名称为必填项"));
                }
                if (!ValidateUtil.isValid(userRowData.getLabelName())) {
                    throw new MyException(String.format("标签名称为必填项"));
                }
                if (labelCache.get(userRowData.getLabelName()) == null) {
                    throw new MyException(String.format("标签不存在：%s", userRowData.getLabelName()));
                }
                if (orgCache.get(userRowData.getOrgName()) == null) {
                    throw new MyException(String.format("机构不存在：%s", userRowData.getOrgName()));
                }
            }

            log.info("=======用户入库");
            log.info("=======" + userRowList.toString());
            // 如果存在则更新
            Date curTime = new Date();
            for (UserRowData userRowData : userRowList) {
                if (!ValidateUtil.isValid(userRowData.getName())) {
                    continue;
                }
                User user = userCache.get(userRowData.getLoginName());
                if (user != null) {
                    user.setParentId(AdminId);
                    user.setType(1);
                    user.setName(userRowData.getName());
                    user.setOrgId(orgCache.get(userRowData.getOrgName()).getId());

                    user.setLabelId(labelCache.get(userRowData.getLabelName()).getId().toString());

                    if (ValidateUtil.isValid(userRowData.getEmail())) {
                        user.setEmail(userRowData.getEmail());
                    }
                    if (ValidateUtil.isValid(userRowData.getPhone())) {
                        user.setPhone(userRowData.getPhone());
                    }
                    if (ValidateUtil.isValid(userRowData.getPwd())) {
                        user.setPwd(userService.getEncryptPwd(user.getLoginName(), userRowData.getPwd()));
                    }
                    String sex = String.valueOf(userRowData.getSex());
                    log.info(sex);
                    if ("男".equals(sex)) {
                        user.setSex("1");
                    }
                    if ("女".equals(sex)) {
                        user.setSex("2");
                    }

                    user.setUpdateTime(curTime);
                    user.setUpdateUserId(getCurUser().getId());
                    userService.update(user);
                    continue;
                }

                // 如果不存在则添加
                user = new User();
                user.setParentId(AdminId);
                user.setType(1);
                user.setLoginName(userRowData.getLoginName());
                user.setName(userRowData.getName());
                user.setOrgId(orgCache.get(userRowData.getOrgName()).getId());

                user.setLabelId(labelCache.get(userRowData.getLabelName()).getId().toString());

                if (ValidateUtil.isValid(userRowData.getEmail())) {
                    user.setEmail(userRowData.getEmail());
                }
                if (ValidateUtil.isValid(userRowData.getPhone())) {
                    user.setPhone(userRowData.getPhone());
                }
                user.setPwd(userService.getEncryptPwd(user.getLoginName(),
                        ValidateUtil.isValid(userRowData.getPwd()) ? userRowData.getPwd() : "111111"));// 初始化密码

                user.setRegistTime(curTime);
                user.setUpdateTime(curTime);
                user.setUpdateUserId(getCurUser().getId());
                user.setState(1);
                if ("男".equals(userRowData.getSex())) {
                    user.setSex("1");
                }
                if ("女".equals(userRowData.getSex())) {
                    user.setSex("2");
                }
                userService.add(user);
            }
        })).sheet().doRead();
    }

    @Override
    public void setDao(BaseDao<Object> dao) {

    }

    @Override
    public List<Map<String, Object>> getListUser(String id) {
        return null;
    }
}
